package com.hspedu.seckill.config;

import com.hspedu.seckill.pojo.User;
import com.hspedu.seckill.service.UserService;
import com.hspedu.seckill.util.CookieUtil;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * UserArgumentResolver: 自定义的一个解析器
 */
@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {
    //装配UserService
    @Resource
    private UserService userService;


    //判断你当前要解析的参数类型是不是你需要的
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //获取参数是不是 user 类型
        Class<?> aClass = parameter.getParameterType();
        //如果为 t, 就执行resolveArgument
        return aClass == User.class;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest webRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {

        // HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        // HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
        //
        // String ticket = CookieUtil.getCookieValue(request, "userTicket");
        // if (!StringUtils.hasText(ticket)) {
        //     return null;
        // }
        //
        // //根据 cookie-ticket 到 Redis 获取 User
        // return userService.getUserByCookie(ticket, request, response);
        return UserContext.getUser();
    }
}
